<?php
/**
 * Created by PhpStorm.
 * User: zxwwjs@hotmail.com
 * Date: 2017-6-28
 * Time: 21:21
 */

namespace App\Repositories;

use App\Repositories\BaseInterface\Repository;
use App\Repositories\Contracts\AttachmentRepositoryInterface;
use Illuminate\Support\Facades\Storage;

class AttachmentRepository extends Repository implements AttachmentRepositoryInterface {

  public function model() {
    return "App\Models\Attachment";
  }

  public function upload( $file ) {
    $files  = [];
    $result = [];
    if ( ! $file ) {
      return null;
    } elseif ( $file instanceof \Illuminate\Http\UploadedFile ) {
      array_push( $files, $file );
    } elseif ( is_array( $file ) ) {
      foreach ( $file as $item ) {
        if ( $item instanceof \Illuminate\Http\UploadedFile ) {
          array_push( $files, $item );
        }
      }
    }
    foreach ( $files as $item ) {
      $data        = [];
      $data['md5'] = md5_file( $item->getRealPath(), false );
      $record      = $this->findBy( 'md5', $data['md5'] );
      if ( $record ) {
        $path     = dirname( $record->filename );
        $fileName = basename( $record->filename );
        $data['filename']=$record->filename;
      } else {
        $data['ext_name']  = strtolower( $file->getClientOriginalExtension() );
        $fileName          = mt_rand( 10000000, 99999999 ) . '.' . $data['ext_name'];
        $path              =  date( 'Y/m/d' );
        $data['filename']  = $path . '/' . $fileName;
        $data['mime_type'] = $file->getClientMimeType();
        $data['size']      = $file->getSize();
        $data['url']       = Storage::url( $data['filename'] );
        $record            = $this->create( $data );
      }
      Storage::putFileAs( $path, $item, $fileName );
      if ( $record ) {
        array_push( $result, $record->toArray() );
      }
    }

    return $result;
  }

}
